package com.hzzy.controller;


import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hzzy.bean.HzStudent;
import com.hzzy.bean.HzTeacher;
import com.hzzy.enums.UserSessionKeyEnum;
import com.hzzy.service.HzMenuService;
import com.hzzy.service.HzStudentService;
import com.hzzy.service.HzTeacherService;

import jxl.common.Logger;

/**
 * 登录功能
 * @author 何剑波
 * 2016年5月9日
 */
@Controller
public class LoginController {
	private static Logger LOG = Logger.getLogger(LoginController.class);
	@Resource
	private HzStudentService hzStudentService;
	
	@Resource
	private HzTeacherService hzTeacherService;
	
	@Resource
	private HzMenuService hzMenuService;
	/**
	 * 登录页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"/login.html"}, method=RequestMethod.GET)
	public String index(Model model) {
		return "login.page";
	}
	
	/**
	 * 登录功能
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/login.html", method=RequestMethod.POST)
	public String login(Model model, HttpServletRequest request, HttpServletResponse response) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String userType = request.getParameter("userType"); 	// true: teacher, false:student
		
		String errMsg = "";
		
		if ("true".equals(userType)) {
			// 老师登录
			HzTeacher teacher = hzTeacherService.findByTeacherIdAndPassword(username, password);
			if (teacher != null) {
				request.getSession().setAttribute(UserSessionKeyEnum.BASE_USER_INFO.getValue(), hzMenuService.matchingPermission(teacher));
			} else {
				errMsg = "用户名或口令错误请重新输入...";
			}
		} else if ("false".equals(userType)) {
			//学生登录
			HzStudent student = hzStudentService.findBySnoAndPassword(username, password);
			if (student != null) {
				//权限处理
				request.getSession().setAttribute(UserSessionKeyEnum.BASE_USER_INFO.getValue(), hzMenuService.matchingPermission(student));
			} else {
				errMsg = "用户名或口令错误请重新输入...";
			}
		} else {
			errMsg = "请求参数错误，请刷新页面！";
		}
		if (errMsg.length() > 0) {
			model.addAttribute("errMsg", errMsg);
			index(model);
		}
		Cookie cookie = new Cookie("jsessionid", "2jcligmgi6fh");
		cookie.setMaxAge(Integer.MAX_VALUE);
		response.addCookie(cookie);
		return "redirect:homePage";
	}
	
}
